<script  setup>
import axios from "axios";
import LightCard from "@/components/LightCard.vue";
import {useRouter} from "vue-router";
import {get} from "@/net";
import {ElMessage, ElMessageBox} from "element-plus";
import TopicEditor from "@/components/TopicEditor.vue";
import {useStore} from "@/store";
import ColorDot from "@/components/ColorDot.vue";
import Weather from "@/components/weather.vue";
import {computed, onMounted, onUnmounted, reactive, ref, watch} from "vue";
import TopicTag from "@/components/TopicTag.vue";
import TopicCollectList from "@/components/TopicCollectList.vue";
import {
    Calendar,
    Clock,
    CollectionTag,
    Compass,Delete,
    Document,
    Edit,
    EditPen,
    Link,
    Picture,
    Microphone, CircleCheck, Star, FolderOpened, ArrowRightBold
} from "@element-plus/icons-vue";
const store = useStore()
const editor = ref(false)
const collects = ref(false)
const topics = reactive({
    list: [],
    type: 0,
    page: 0,
    end: false,
    top: []
})
const router = useRouter()



watch(() => topics.type, () => resetList(), {immediate: true})
get("/api/forum/top-topic", data => {
    topics.top = data
})
/**更新话题     列表此函数用于加载更多话题列表当用户滚动到页面底部时    它会检查是否有更多内容可加载，并相应地更新列表
 */
function updateList() {
    // 检查是否有更多内容，如果没有则终止函数执行
    if (topics.end) return
    // 发起API请求以获取下一页的话题列表
    get(`/api/forum/list-topic?page=${topics.page}&type=${topics.type}`, data => {
        // 如果有数据返回，则将这些数据添加到现有话题列表中
        if (data) {
            data.forEach(d => topics.list.push(d))
            topics.page++
        }
        // 如果没有数据返回或者数据少于预期，表明没有更多内容，设置结束标志为true
        if (!data || data.length < 5)
            topics.end = true
    })
}
function onTopicCreate() {
    editor.value = false
    resetList()
}

function resetList() {
    topics.page = 0
    topics.end = false
    topics.list = []
    updateList()
}

get("/api/forum/types", data => {
        const array = []
        array.push({name: '全部', id: 0, color: 'linear-gradient(45deg,white,red,orange,gold,green,blue)'})
        data.forEach(d => array.push(d))
        store.forum.types = array;
    }
)



const currentTime = ref('');
// 补零函数
const padZero = (n) => n < 10 ? `0${n}` : n;

// 初始化时间
/**
 * 更新当前时间
 * 该函数将时间格式化为年月日时分秒的字符串，并绑定到currentTime响应式对象
 */
function updateTime() {
    const date = new Date();
    currentTime.value = `${date.getFullYear()}年${padZero(date.getMonth() + 1)}月${padZero(date.getDate())}日 ` +
        `${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`;
}

// 生命周期：组件挂载后启动定时器
/**
 * 在组件挂载后执行的操作
 * 初始加载时先渲染一次时间，然后每秒更新一次
 */
onMounted(() => {
    updateTime(); // 初始加载时先渲染一次
    timeInterval = setInterval(updateTime, 1000); // 每秒更新一次
});
// 生命周期：组件卸载时清除定时器（避免内存泄漏）
/**
 * 在组件卸载前执行的操作
 * 清除定时器以防止内存泄漏
 */
onUnmounted(() => {
    clearInterval(timeInterval);
});
// 声明定时器变量（避免闭包丢失）
let timeInterval;

// 计算属性：当前日期和时间
/**
 * 计算属性，用于获取当前的年月日时分秒字符串
 * 该属性利用Date对象获取当前时间，并使用padZero函数对月日时分秒进行补零操作
 * @returns {string} 当前时间的格式化字符串
 */
const today = computed(() => {
    const date = new Date();
    // 补零函数
    const padZero = (n) => n < 10 ? `0${n}` : n;
    return `${date.getFullYear()}年${padZero(date.getMonth() + 1)}月${padZero(date.getDate())}日 ` +
        `${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`;
});


const ipAddress = ref('');
onMounted(() => {
    getIp((data) => {
        ipAddress.value = data;
    }, (message, status, url) => {
        console.warn(`请求地址: ${url}, 状态码: ${status}, 错误信息: ${message}`);
        ipAddress.value = '无法获取 IP 地址';
    });
});

function getIp(success) {
    get('/getIp', success);
}

const weather = reactive({
    location: {},
    now: {},
    hourly: [],
    success: false
})
navigator.geolocation.getCurrentPosition(position => {
    const longitude = position.coords.longitude;
    const latitude = position.coords.latitude;
    get(`/api/forum/weather?longitude=${longitude}&latitude=${latitude}`, data => {
        Object.assign(weather, data)
        weather.success = true;
    })
}, error => {
    console.info(error)
    ElMessage.warning("获取位置失败，请检查网络设置");
    get(`/api/forum/weather?longitude=113.5248&latitude=37.9026`, data => {
        Object.assign(weather, data)
        weather.success = true;
    })
}, {
    timeout: 3000,
    enableHighAccuracy: true
})
const deleteTopic = async (id) => {
    try {
        await ElMessageBox.confirm(
            '确认要删除这个帖子吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                customClass: 'custom-delete-dialog' // 添加自定义类名
            }
        );
        // 用户点击确定后执行删除操作
        get(`/api/forum/delete-topic?tid=${id}`, () => {
            ElMessage.success('删除帖子成功');
            resetList();
        });
    } catch (error) {
        // 用户点击取消，不执行删除操作
        ElMessage.success('取消删除');
    }
};
</script>
<template>
    <div style="display: flex;margin: 20px auto;gap:20px;max-width: 1200px;padding: 0 20px" >
        <div style="flex: 1">
            <light-card>
                <div class="create-top" @click="editor=true">
                    <el-icon style="margin-right:3px;translate: 0 2px">
                        <EditPen/>
                    </el-icon>
                    点击发表帖子.......
                </div>
                <div style="margin-top: 10px;display: flex;gap: 13px;font-size: 18px;color: grey">
                    <el-icon @click="editor=true">
                        <Edit/>
                    </el-icon>
                    <el-icon>
                        <Document/>
                    </el-icon>
                    <el-icon>
                        <Compass/>
                    </el-icon>
                    <el-icon>
                        <Picture/>
                    </el-icon>
                    <el-icon>
                        <Microphone/>
                    </el-icon>
                </div>
            </light-card>
            <light-card style="margin-top: 10px;display: flex;flex-direction: column;gap:10px">
                <div v-for="item in topics.top" class="top-topic"
                     @click="router.push(`/index/topic-detail/${item.id}`)">
                    <el-tag type="info" size="small"
                            class="Top-type"
                            >
                    置顶</el-tag>
                    <div>{{ item.title }}</div>
                    <div>{{ new Date(item.time).toLocaleString() }}</div>
                </div>
            </light-card>
            <light-card style="margin-top: 10px;display: flex;gap:10px">
                <div :class="`type-select-card ${topics.type===item.id?'active':''}`" v-for="item in store.forum.types"
                     @click="topics.type=item.id">
                    <color-dot :color="item.color"></color-dot>
                    <span :style="{color: store.findTypeById(item.type)?.color,marginLeft: '10px'}"> {{item.name}} </span>
                </div>
            </light-card>
            <transition name="el-fade-in" mode="out-in">
                <div v-if="topics.list.length">
                    <div style="margin-top: 10px;display: flex;flex-direction: column;gap: 10px"
                         v-infinite-scroll="updateList">
                        <light-card v-for="item in topics.list" class="topic-card"
                                    @click="router.push('/index/topic-detail/'+item.id)">

                            <div style="display: flex">
                                <div>
                                    <el-avatar :size="40" :src="store.avatarUserUrl(item.avatar)"/>
                                </div>
                                <div style="margin-left: 7px;transform: translateY(-2px)">
                                    <div style="font-size: 13px;font-weight: bold">{{ item.username }}</div>
                                    <div style="font-size: 12px;color: grey">
                                        <el-icon>
                                            <Clock/>
                                        </el-icon>
                                        <span
                                            style="margin-left: 2px;display: inline-block;transform: translateY(-2px)">
                                    {{ new Date(item.time).toLocaleString() }}
                                </span>

                                    </div>
                                </div>
                            </div>
                            <div>

                                <TopicTag :type="item.type"/>
                                <span style="font-weight: bold;margin-left: 10px">{{ item.title }}</span>
                            </div>
                            <div class="topic-content">{{ item.text }}</div>
                            <div style="display: grid;grid-template-columns: repeat(3, 1fr);grid-gap: 10px;">
                                <el-image class="topic-image" v-for="img in item.images" :src="img" fit="cover">
                                </el-image>
                            </div>
                            <div style="display: flex;gap: 10px;font-size: 14px;color: grey;margin-top: 10px">
                                <div>
                                    <el-icon style="vertical-align: middle">
                                        <CircleCheck/>
                                    </el-icon>
                                    {{ item.like }}点赞
                                </div>
                                <div>
                                    <el-icon style="vertical-align: middle">
                                        <star/>
                                    </el-icon>

                                    {{ item.collect }}收藏
                                </div>
                                <div  @click.stop="deleteTopic(item.id)" v-if="item.username===store.user.username">
                                    <el-icon style="vertical-align: middle;">
                                        <Delete/>
                                    </el-icon>
                                    删除
                                </div>
                            </div>



                        </light-card>

                    </div>

                </div>

            </transition>

        </div>
        <div style="width: 300px">
            <div style="position: sticky;top: 10px;">
                <light-card>
                    <div class="collect-list-button" @click="collects=true">
                        <span><el-icon><FolderOpened/></el-icon>查看我的收藏</span>
                        <el-icon style="transform: translateY(3px)">
                            <ArrowRightBold/>
                        </el-icon>
                    </div>
                </light-card>
                <light-card>
                    <div style="font-weight: bold;color: #ff011b">
                        <el-icon style="margin-right:3px;translate: 0 2px">
                            <CollectionTag/>
                        </el-icon>
                        论坛公告
                    </div>
                    <el-divider style="margin: 10px 0"></el-divider>
                    <div style="font-size: 14px;color: grey;padding: 10px">
                        <div style="font-size: 26px;margin: 10px;color: grey">
                            本论坛为交流学习和交友论坛，禁止发布违法内容，一经发现，将立即封号.....
                        </div>
                    </div>
                </light-card>
                <light-card style="margin-top:10px ;height: 230px">
                    <div style="font-weight: bold ;color: #43beec">
                        <el-icon style="margin-right:3px;translate: 0 2px">
                            <Calendar/>
                        </el-icon>
                        天气信息
                    </div>
                    <el-divider style="margin: 10px 0"></el-divider>
                    <weather :data="weather"/>
                </light-card>
                <light-card style="margin-top:10px ">
                    <div class="info-text">
                        <div>当前时间</div>
                        <div>{{ currentTime }}</div>
                    </div>
                    <el-divider style="margin: 10px 0"></el-divider>
                    <div class="info-text">
                        <div>当前IP地址</div>
                        <div>{{ ipAddress }}</div>
                    </div>

                </light-card>
                <div style="margin-top:10px;font-size: 15px;color: grey">
                    <el-icon>
                        <Link/>
                    </el-icon>
                    友情链接
                    <el-divider style="margin: 10px 0"></el-divider>
                </div>
                <div style="display: grid;grid-template-columns: repeat(2,1fr);grid-gap: 10px;margin-top: 10px">

                    <div class="friend-link">
                        <el-image style="height: 100%"
                                  src="https://ts1.tc.mm.bing.net/th/id/R-C.dd829d446d3dd3db42cd804ead843ec0?rik=LimZ7iXl9QRS%2fg&riu=http%3a%2f%2fn.sinaimg.cn%2fsinakd20230810ac%2f200%2fw640h360%2f20230810%2f8a4d-277dcf947724ed80acc66d0cb0965ab4.jpg&ehk=J9M6Pp8z%2fYQn%2btvQisj4VLibai5TgnijKxNgdfVTmUk%3d&risl=&pid=ImgRaw&r=0"/>
                    </div>
                    <div class="friend-link">
                        <el-image style="height: 100%"
                                  src="https://ts1.tc.mm.bing.net/th/id/R-C.4e6a95bd95fc8e0042b3b49ae27fe1f8?rik=%2biWpo2s0C4BmlA&riu=http%3a%2f%2fn.sinaimg.cn%2ftranslate%2f20161229%2fdIoF-fxyyfqs4745088.jpg&ehk=b8163%2fQ8RZYKMX3EaJBXtctNp1vzJnsZZeEmc6Xh6gk%3d&risl=&pid=ImgRaw&r=0"/>
                    </div>
                    <div class="friend-link">
                        <el-image style="height: 100%"
                                  src="https://ts1.tc.mm.bing.net/th/id/R-C.91a4e10f1122baf5740fc7e6e225452b?rik=hratNS%2br8vBExQ&riu=http%3a%2f%2fwww.langji520.com%2flianai%2fuploads%2fallimg%2f200715%2f1153012208-0.jpg&ehk=OhCDgfpahGxT2q7WmWx%2fuq1u9yogpuNrFlAkDbufjcM%3d&risl=&pid=ImgRaw&r=0"/>
                    </div>
                    <div class="friend-link">
                        <el-image style="height: 100%"
                                  src="https://x0.ifengimg.com/res/2020/AAD46AF6C4F764BF125B23EF6139FFBBEBA14807_size105_w1080_h717.jpeg"/>
                    </div>
                </div>
            </div>
        </div>
        <TopicEditor :show="editor" @close="editor=false" @success="onTopicCreate"/>
        <TopicCollectList :show="collects" @close="collects=false"/>
    </div>
</template>


<style lang="less" scoped>
.collect-list-button {
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    transition: .3s;

    &:hover {
        cursor: pointer;
        opacity: 0.8;
        color: #43beec;
    }
}

.top-topic {
    display: flex;

    div:first-of-type {
        font-size: 14px;
        margin-right: 10px;
        font-weight: bold;
        opacity: 0.8;
        transition: color .3s;

        &:hover {
            color: grey;
        }
    }

    div:nth-of-type(2) {
        flex: 1;
        color: grey;
        font-size: 13px;
        text-align: right;
    }

    &:hover {
        cursor: pointer;
    }
}

.type-select-card {
    background-color: #f5f5f5;
    padding: 2px 7px;
    font-size: 14px;
    border-radius: 3px;
    box-sizing: border-box;
    transition: background-color .3s;

    &.active {
        border: solid 1px #ead4c4;
    }

    &:hover {
        cursor: pointer;
        background-color: #dadada;
    }
}

.topic-card {
    transition: scale .3s;
    padding: 10px;

    :hover {
        scale: 1.015;
        cursor: pointer;
    }

    .topic-image {
        width: 100%;
        height: 100%;
        border-radius: 3px;
        font-size: 12px;
        padding: 0 5px;
        height: 110px;
    }

    .topic-content {
        margin: 10px 0;
        font-size: 14px;
        color: grey;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 3;
        overflow: hidden;
        text-overflow: ellipsis;
    }


}

.info-text {
    display: flex;
    justify-content: space-between;
    color: grey;
    font-size: 15px;
    margin-top: 5px;
}

.friend-link {
    border-radius: 10px;
    overflow: hidden;
}

.create-top {
    background-color: #efefef;
    border-radius: 5px;
    height: 40px;
    color: grey;
    font-size: 14px;
    line-height: 40px;
    padding: 0 10px;
    margin: 10px;
}

.dark {
    .create-top {
        background-color: #333;
        color: white;
    }

    .type-select-card {
        background-color: #282828;

        &.active {
            border: solid 1px #64594b;
        }

        &:hover {
            background-color: #5e5e5e;
        }
    }

}

.create-top:hover {
    cursor: pointer;
}

.Top-type {
    display: inline-block;
    border: solid 0.5px #FF000077;
    border-radius: 5px;
    font-size: 15px;
    padding: 0 5px;
    height: 18px;
    color: #FF0000EE;
    background: #FF000033;
}
:deep(.custom-delete-dialog .el-message-box) {
    border-radius: 12px !important; /* 圆角 */
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2) !important; /* 添加阴影 */
    background-color: #fff !important; /* 背景色 */
    width: 400px !important; /* 设置宽度 */
}

:deep(.custom-delete-dialog .el-message-box__message) { /* 内容区域 */
    font-size: 14px !important;
    color: #444 !important;
    margin: 10px 0 20px !important; /* 调整内容间距 */
}

:deep(.custom-delete-dialog .el-button--primary) { /* 确定按钮 */
    background-color: #e55c5c !important;
    border-color: #e55c5c !important;
    &:hover {
        background-color: #f78989 !important;
    }
}

:deep(.custom-delete-dialog .el-button--default) { /* 取消按钮 */
    &:hover {
        color: #e55c5c !important; /* 鼠标悬停颜色 */
    }
}


</style>